import api from "../../apis/forms";

Page({
  data: {
    headerLayout: {
      title: "报名",
      paddingBottom: 7,
      back: true,
    },
    id: -1,
    formLayout: [],
    formData: [],
    wjxurl: '', // 默认 URL
  },
  onLoad() {
    const initialUrl = "https://www.wjx.cn/vm/e9RsnFB.aspx?width=750&source=iframe&s=t";
    this.setData({ wjxurl: initialUrl });
  },
  onInput(e) {
    const detail = e.detail;
    const index = e.currentTarget.dataset.index;
    this.setData({
      [`formData[${index}].id`]: detail.id,
      [`formData[${index}].data`]: detail.data.value,
    })
  },
  cancel: () => wx.navigateBack(),
  toast() {
    wx.showToast({
      icon: "error",
      title: "数值不可为空"
    })
  },
  check() {
    if (this.data.formData.length !== this.data.formLayout.length) {
      this.toast();
      return false;
    }
    let success = true;

    for (let index = 0; index < this.data.formData.length; index++) {
      if (this.data.formData[index].id !== this.data.formLayout[index].id) {
        success = false;
        break;
      }
    }
    if (!success) this.toast();
    return success;
  },
  async submit() {
    if (!this.check()) return;
    try {
      const url = await api.signUpActivity(this.data.id, this.data.formData);
      console.log(url);
      wx.navigateTo({
        url: `/pages/success/index${url != null ? `?image=${url}` : ""}`
      })
    } catch (e) {
      setTimeout(() =>
        wx.navigateBack({
          delta: 2
        }), 2000)
    }
  },
  // onLoad: async function (options) {
  //   const id = options["id"];
  //   const layout = await api.getFormLayout(id);
  //   this.setData({
  //     id: id,
  //     formLayout: layout,
  //     formData: Array.from({length: layout.length}, () => ({}))
  //   })
  // }
});
